/**
 * Created by kinfen on 2016/12/15.
 */
const fs = require('fs');
var key = [];
var tinify = require('tinify');
const through = require('through-gulp');
const gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var keyIndex = 0;
var accountErrorCounter = 0;
const {fileSize} = require('../file');

const PLUGIN_NAME = "kadm-tinypng";

function gulpPrefixer(options) {
    key = options.keys;
    tinify.key = options.keys[keyIndex];
    if (!key || key.length == 0){
        throw new PluginError(PLUGIN_NAME, "请确保 tinify的 cache, key等参数正确");
    }

    // Creating a stream through which each file will pass
    var stream = through(function(file, enc, callback) {
        if (file.isNull()) {
            this.push(file); // Do nothing if no contents
            return callback();
        }
        if (file.isBuffer()) {
            var prevLength = file.contents.length;
            tinypng(file, function(err, data) {
                if (!err){
                    file.contents = data;
                    this.push(file);
                    gutil.log(`gulp_tinypng:${gutil.colors.green('✔ ') + file.relative} ${fileSize(prevLength)} => ${fileSize(data.length)}`);
                    return callback();
                }
                else{
                    this.push(null);
                    gutil.log(`gulp_tinypng:Error With ${err}`);
                    return callback();
                }

            }.bind(this));
        }

        if (file.isStream()) {
            throw new PluginError(PLUGIN_NAME, "Stream is not supported");
            return callback();
        }
    });

    // returning the file stream
    return stream;
};

function gulpImageResize(options) {
    key = options.keys;
    let resize = options.resize;
    tinify.key = options.keys[keyIndex];
    if (!key || key.length == 0){
        throw new PluginError(PLUGIN_NAME, "请确保 tinify的 cache, key等参数正确");
    }

    // Creating a stream through which each file will pass
    var stream = through(function(file, enc, callback) {
        if (file.isNull()) {
            this.push(file); // Do nothing if no contents
            return callback();
        }
        if (file.isBuffer()) {
            var prevLength = file.contents.length;

            tinypngResize(file, resize, function(err, data) {
                if (!err){
                    file.contents = data;
                    this.push(file);
                    gutil.log(`gulp_tinypng:${gutil.colors.green('✔ ') + file.relative} ${fileSize(prevLength)} => ${fileSize(data.length)}`);
                    return callback();
                }
                else{
                    this.push(null);
                    gutil.log(`gulp_tinypng:Error With ${err}`);
                    return callback();
                }

            }.bind(this));
        }

        if (file.isStream()) {
            throw new PluginError(PLUGIN_NAME, "Stream is not supported");
            return callback();
        }
    });

    // returning the file stream
    return stream;
};
var tinypngResize = function(file, opts, cb){
    tinify.fromBuffer(file.contents).resize(opts).toBuffer(function(err, resultData) {
        if (err){
            if (err instanceof tinify.AccountError){
                if (accountErrorCounter++ < key.length - 1){
                    gutil.log(`tinypng帐号错误,apikey失效或到达调用上限,将切换下一个key`);
                    keyIndex =  (keyIndex + 1) % key.length;
                    tinify.key = key[keyIndex]
                    gutil.log(`使用 key:${key[keyIndex]}`);
                    tinypng(file, cb);
                    return;

                }
                else{
                    gutil.log(`apikey 已用完, 无法从tinypng调整图片,请添加新的apikey或者等下个月`);
                }
                // Verify your API key and account limit.
            } else if (err instanceof tinify.ClientError) {
                // Check your source image and request options.
            } else if (err instanceof tinify.ServerError) {
                // Temporary issue with the Tinify API.
            } else if (err instanceof tinify.ConnectionError) {
                // A network connection error occurred.
            } else {
                // Something else went wrong, unrelated to the Tinify API.
            }
            cb(err, null)
        }
        else{

            cb(null, resultData);
        }

    });
}
var tinypng = function(file, cb) {
    tinify.fromBuffer(file.contents).toBuffer(function(err, resultData) {
        if (err){
            if (err instanceof tinify.AccountError){
                if (accountErrorCounter++ < key.length - 1){
                    gutil.log(`tinypng帐号错误,apikey失效或到达调用上限,将切换下一个key`);
                    keyIndex =  (keyIndex + 1) % key.length;
                    tinify.key = key[keyIndex]
                    gutil.log(`使用 key:${key[keyIndex]}`);
                    tinypng(file, cb);
                    return;

                }
                else{
                    gutil.log(`apikey 已用完, 无法从tinypng压缩图片,请添加新的apikey或者等下个月`);
                }
                // Verify your API key and account limit.
            } else if (err instanceof tinify.ClientError) {
                // Check your source image and request options.
            } else if (err instanceof tinify.ServerError) {
                // Temporary issue with the Tinify API.
            } else if (err instanceof tinify.ConnectionError) {
                // A network connection error occurred.
            } else {
                // Something else went wrong, unrelated to the Tinify API.
            }
            cb(err, null)
        }
        else{

            cb(null, resultData);
        }

    });
}
exports.tinifycompress = gulpPrefixer;
exports.tinifyresize = gulpImageResize;
// module.exports = gulpPrefixer;

